package dao.impl;

import dao.AdminDao;
import entity.Admin;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import utils.DbUtil;

import java.util.List;

/**
 * Created by honghao on 2017/2/6.
 */
public class AdminDaoImpl implements AdminDao {
    private static SessionFactory sf = DbUtil.getSf();
    @Override
    public Admin get(int id) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        Admin admin = (Admin) session.get(Admin.class, id);
        tx.commit();
        return admin;
    }

    @Override
    public void save(Admin admin) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        session.save(admin);
        tx.commit();
    }

    @Override
    public void delete(Admin admin) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        session.delete(admin);
        tx.commit();
    }

    @Override
    public void delete(int id) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        Admin admin = (Admin) session.get(Admin.class, id);
        session.delete(admin);

        tx.commit();
    }

    @Override
    public void update(Admin admin) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        session.update(admin);
        tx.commit();
    }

    @Override
    public List<Admin> findAdminByNameAndPass(String name, String pass) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        Query query = session.createQuery("from Admin where username=? and password=?");

        query.setParameter(0, name);
        query.setParameter(1, pass);

        List list = query.list();
        tx.commit();
        return list;
    }
}
